'use client';

import type { IDraft, IPostEditInfo, IPostNewInfo } from '@/interfaces';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  queryEditPostDrafts,
  queryPostDrafts,
  removeDraft,
} from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import type { TBody } from '@/types';
import classNames from 'classnames';
import { useState } from 'react';
import { formatDate } from '@/lib/tool';
import useToast from '@/hooks/useToast';
import type { TViewDraftTranslatedField } from '@/app/[locale]/posts/[id]/edit/draft/view';
import ViewDraft from '@/app/[locale]/posts/[id]/edit/draft/view';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export type TDraftTranslatedField = 'nodata' | 'deleteAll' | 'deleteCompleted';

export default function Draft(
  this: any,
  {
    source,
    translatedFields = {
      nodata: '暂无草稿',
      deleteAll: '删除所有',
      deleteCompleted: '删除完成',
    },
    viewTranslatedFields,
  }: {
    source: IPostEditInfo | IPostNewInfo;
    translatedFields?: Record<TDraftTranslatedField, any>;
    viewTranslatedFields?: Record<TViewDraftTranslatedField, any>;
  },
) {
  const isEdit = 'basic' in source;
  const [currentItemId, setCurrentItemId] = useState<number>();
  const [currentItem, setCurrentItem] = useState<IDraft>();
  const newPostQueryKey = ['/forum', '/drafts', '/posts', '/new'];
  const editPostQueryKey = [
    '/forum',
    '/drafts',
    '/posts',
    isEdit ? source.basic.id : undefined,
    '/edit',
  ];
  const queryKey = isEdit ? editPostQueryKey : newPostQueryKey;
  const { show } = useToast();
  const [isDeleteALl, setIsDeleteALl] = useState(false);
  const queryClient = useQueryClient();

  const queryNewPostDraftsQuery = useQuery(
    newPostQueryKey,
    async () => {
      return (await queryPostDrafts()) as IDraft[];
    },
    {
      enabled: !isEdit,
    },
  );
  const queryEditPostDraftsQuery = useQuery(
    editPostQueryKey,
    async (context) => {
      return (await queryEditPostDrafts({
        id: context.queryKey[3] + '',
      })) as IDraft[];
    },
    {
      enabled: isEdit,
    },
  );

  const removeDraftMutation = useMutation(async (variables: TBody<void>) => {
    await removeDraft(variables);
  });

  async function onClickDeleteAll() {
    try {
      setIsDeleteALl(true);

      const drafts =
        queryEditPostDraftsQuery.data || queryNewPostDraftsQuery.data || [];
      await Promise.all(
        drafts.map((value) =>
          removeDraftMutation.mutateAsync({
            id: value.id + '',
          }),
        ),
      );

      await queryClient.refetchQueries({ queryKey }, { throwOnError: true });
      setCurrentItem(undefined);

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteCompleted,
      });
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setIsDeleteALl(false);
    }
  }

  function onClickItem(item: IDraft) {
    setCurrentItem(item);
    setCurrentItemId(item.id);
  }

  if (queryNewPostDraftsQuery.data || queryEditPostDraftsQuery.data) {
    let drafts;
    if (isEdit) {
      drafts = queryEditPostDraftsQuery.data || [];
    } else {
      drafts = queryNewPostDraftsQuery.data || [];
    }

    return (
      <div className="card border-0">
        <div className="card-body d-flex flex-column gap-4 my-4">
          <button
            disabled={drafts.length === 0 || isDeleteALl}
            className="btn btn-danger col-6 col-lg-2 text-truncate text-nowrap"
            onClick={onClickDeleteAll}
          >
            {isDeleteALl ? (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            ) : (
              <i className="bi bi-trash me-2"></i>
            )}
            {translatedFields.deleteAll}
          </button>

          <div className="row mt-4 g-4">
            <div className="col-12 col-lg">
              {drafts.length > 0 && (
                <div className="list-group">
                  {drafts.map((item) => {
                    return (
                      <div
                        key={item.id}
                        className={classNames(
                          'card border text-secondary border-1 mb-3 list-group-item list-group-item-action cursor-pointer',
                          {
                            active: currentItemId === item.id,
                          },
                        )}
                        onClick={onClickItem.bind(this, item)}
                      >
                        <div className="card-body px-0 py-2">
                          <div className="row">
                            <div className="col-3 m-auto text-center ms-0">
                              <i
                                className={classNames(
                                  'bi bi-compass fs-2',
                                  currentItemId === item.id
                                    ? 'text-white'
                                    : 'text-secondary',
                                )}
                              ></i>
                            </div>
                            <div className="col-8 align-self-center">
                              {item.name && (
                                <p className="card-text mb-2">
                                  <small
                                    className={classNames(
                                      currentItemId === item.id
                                        ? 'text-white'
                                        : 'text-secondary',
                                    )}
                                  >
                                    {item.name}
                                  </small>
                                </p>
                              )}

                              <p
                                className={classNames(
                                  'card-title mb-0 text-truncate',
                                  currentItemId === item.id
                                    ? 'text-white'
                                    : 'text-secondary',
                                )}
                              >
                                <time dateTime={item.createdOn}>
                                  {formatDate(item.createdOn)}
                                </time>
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {drafts.length === 0 && <Nodata />}
            </div>

            {currentItem && (
              <div className="col">
                <ViewDraft
                  queryKey={queryKey}
                  currentItem={currentItem}
                  setCurrentItem={setCurrentItem}
                  translatedFields={viewTranslatedFields}
                />
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  if (queryNewPostDraftsQuery.error || queryEditPostDraftsQuery.error) {
    let error;
    if (isEdit) {
      error = queryNewPostDraftsQuery.error;
    } else {
      error = queryEditPostDraftsQuery.error;
    }

    return <Alert type="error" message={error} />;
  }

  return <AlertLoad />;
}
